---
import DefaultLayout from '../../layouts/DefaultLayout.astro'
import { Card, Pagination } from 'accessible-astro-components'

export async function getStaticPaths({ paginate }) {
  const response = await fetch('https://jsonplaceholder.typicode.com/posts')
  const data = await response.json()

  return paginate(data, { pageSize: 6 })
}

const { page } = Astro.props
---

<DefaultLayout
  title="Blog"
  description="An example of a blog with dynamic content fetched from JSONPlaceholder using the title, body and userId."
>
  <section class="my-12">
    <div class="space-content container">
      <h1>Blog</h1>
      <p class="text-2xl">
        An example of a blog with dynamic content fetched from <a href="https://jsonplaceholder.typicode.com/posts"
          >JSONPlaceholder</a
        > using the title, body and userId. The Accessible Astro Card Component is used here to display al the posts.
      </p>
    </div>
  </section>
  <section class="my-12">
    <div class="container">
      <p class="text-sm"><em>Post {page.start + 1} through {page.end + 1} of {page.total} total posts</em></p>
      <ul class="my-3">
        {
          page.data.map((post) => (
            <li>
              <Card
                url={'/blog/' + post.title.replaceAll(' ', '-').toLowerCase()}
                title={post.title}
                footer={'userId:' + post.userId}
              >
                {post.body}
              </Card>
            </li>
          ))
        }
      </ul>
      <div class="mt-12 grid place-content-center">
        <Pagination
          firstPage={page.url.prev ? '/blog' : null}
          previousPage={page.url.prev ? page.url.prev : null}
          nextPage={page.url.next ? page.url.next : null}
          lastPage={page.url.next ? `/blog/${Math.round(page.total / page.size)}` : null}
          currentPage={page.currentPage}
          totalPages={Math.round(page.total / page.size)}
        />
      </div>
    </div>
  </section>
</DefaultLayout>

<style lang="scss">
  ul {
    display: grid;
    grid-template-columns: 1fr;
    grid-gap: 4rem;

    @media (min-width: 550px) {
      grid-template-columns: repeat(2, 1fr);
      grid-gap: 2rem;
    }

    @media (min-width: 950px) {
      grid-template-columns: repeat(3, 1fr);
    }
  }
</style>
